<?php


class Admin_model extends Base_model {

	/**
	 * 表名
	 * 
	 * @param string 
	 */
    public $_table_name = "admin";


    /**
     * status状态：1 正常    2 禁止
     */
    const STATUS_SUCCESS = 1;
    const STATUS_FAILED = 2;


     /**
     * 状态数组
     * @var array 
     */
	public static $status_arr = array(self::STATUS_SUCCESS => '正常', self::STATUS_FAILED => '禁止');


    /**
     * 状态
     * @var string 
     */
    public $status;


    /**
     * 用户名
     * @var string 
     */
    public $username;


    /**
     * 角色ID
     * @var int 
     */
    public $role_id;


	/**
     * 密码
     * @var string 
     */
    public $password;


	/**
     * 密码盐
     * @var string 
     */
    public $salt;


    /**
     * 登录次数
     * @var int 
     */
    public $logins;


	/**
     * 昵称(真实姓名)
     * @var string 
     */
    public $nickname;


	/**
     * 手机号
     * @var string 
     */
    public $mobile;


	/**
     * email地址
     * @var string 
     */
    public $email;


	/**
     * 最后登录IP
     * @var string 
     */
    public $last_ip;


	/**
     *最后登录时间
     * @var int 
     */
    public $last_time;


	/**
     * 创建时间
     * @var int 
     */
    public $create_time;



    /**
     * 插入数据前验证
     * 
     * @return boolean 
     */
    protected function prepare_insert()
	{
		if(empty($this->username) OR empty($this->role_id) OR empty($this->password) OR empty($this->salt))
		{
            return false;
        }

		//默认值
        if(empty($this->status))
		{
            $this->status = self::STATUS_SUCCESS;
        }

        if(empty($this->nickname))
		{
            $this->nickname = $this->username;
        }

        if(empty($this->create_time))
		{
            $this->create_time = time();
        }

        return true;
    }


    
    /**
     * 搜索
     * 
     * @return boolean true | false
     */
    public function search()
	{
        $sql = "SELECT ";

        if(!empty($this->_selected_fields))
		{
			if (is_array($this->_selected_fields))
			{
				$sql .= implode(", ", $this->_selected_fields);
			}
			else
			{
				$sql .= $this->_selected_fields;
			}
        }
		elseif (!empty($this->_is_search_counter))
		{
            $sql .= " COUNT(adur.id) AS rows_total ";
        }
		else
		{
            $sql .= " adur.* ";
        }

        $sql .= " FROM {$this->_table_name} AS adur ";

        $statement = "";
        $where = array();

        if (!empty($this->id))
		{
            $statement .= " AND adur.id = ? ";
            $where[] = $this->id;
        }

        if (!empty($this->status))
		{
            $statement .= " AND adur.status = ? ";
            $where[] = $this->status;
        }

        if (!empty($this->role_id))
		{
            $statement .= " AND adur.role_id = ? ";
            $where[] = $this->role_id;
        }

        if (!empty($this->username))
		{
            $statement .= " AND adur.username = ? ";
            $where[] = $this->username;
        }

		//LIKE模糊搜索用户名
        if (!empty($this->_username_like))
		{
            $statement .= " AND adur.username LIKE '%" . $this->db->escape_like_str($this->_username_like). "%' ";
        }

        if (!empty($this->nickname))
		{
            $statement .= " AND adur.nickname LIKE '%" . $this->db->escape_like_str($this->nickname). "%' ";
        }


		//处理条件
        if($statement)
		{
            $sql .= " WHERE " . substr($statement, 4);
        }

        if (!empty($this->_group_by))
		{
            $sql .= " GROUP BY {$this->_group_by} ";
        }

        if (!empty($this->_is_search_counter))
		{
            $sql .= " LIMIT 1";
        }
		else
		{
            if (!empty($this->_order_by))
			{
                $sql .= " ORDER BY {$this->_order_by} ";
            }

			//是否分页
            if ($this->is_paging())
			{
				$page_from = ($this->_page_index - 1) * $this->_page_count;

                $sql .= " LIMIT {$page_from}, {$this->_page_count}";
            }
        }

        $result = $this->db->query($sql, $where);

        if(empty($this->_is_search_counter))
		{
			$this->_search_results = $result->result();
        }
		else
		{
            if ($result->num_rows() > 0)
			{
                $row = $result->row();

                if (!empty($row->rows_total))
				{
                    $this->_search_num_rows = $row->rows_total;
                }
            }
        }

        $result->free_result();

        return true;
    }


    /**
     * 根据用户名获取合法用户
     * 
     * @param string $username  后台管理员用户名
     * 
     * @return boolean | object
     */
    public function get_admin_by_username($username)
	{
        if(empty($username))
		{
            return false;
        }

        $sql = "SELECT a.* FROM {$this->_table_name} AS a
					LEFT JOIN {$this->db->dbprefix}admin_role AS r ON a.role_id = r.id
					WHERE a.username = ? 
					AND a.status = " . self::STATUS_SUCCESS . " 
					AND r.status = 1 
					LIMIT 1";

        $result = $this->db->query($sql, array($username));

		return $result->row();
	}


    /**
     * 根据用户id获取合法用户
     * 
     * @param int $user_id  用户id
     * 
     * @return boolean | object
     */
    public function get_admin_by_id($user_id)
	{
        if(empty($user_id))
		{
            return false;
        }

        $sql = "SELECT a.*, r.role_name, r.permissions FROM {$this->_table_name} AS a
					LEFT JOIN {$this->db->dbprefix}admin_role AS r ON a.role_id = r.id
					WHERE a.id = ? 
					AND a.status = " . self::STATUS_SUCCESS . " 
					AND r.status = 1 
					LIMIT 1";

        $result = $this->db->query($sql, array($user_id));

		return $result->row();
	}


    /**
     * 根据用户名及用户id判断用户是否已经存在(用于添加或修改用户名时判断是否用户名已被占用)
     * 
     * @param int $username  用户名
     * @param int $id  用户id
     * 
     * @return boolean true | false
     */
    public function check_exist_by_username_or_id($username, $id = 0)
	{
        if(empty($username))
		{
            return false;
        }

        $sql = "SELECT a.id FROM {$this->_table_name} AS a
					WHERE a.username = ? 
					AND a.id != ?
					LIMIT 1";

        $result = $this->db->query($sql, array($username, $id));

        if(empty($result->row()))
		{
            return false;
        }
		else
		{
            return true;
		}
	}


    /**
     * 根据email地址及用户id判断邮箱是否已被占用
     * 
     * @param int $email  邮箱地址
     * @param int $id  用户id
     * 
     * @return boolean true | false
     */
    public function check_exist_by_email_or_id($email, $id = 0)
	{
        if(empty($email))
		{
            return false;
        }

        $sql = "SELECT a.id FROM {$this->_table_name} AS a
					WHERE a.email = ? 
					AND a.id != ?
					LIMIT 1";

        $result = $this->db->query($sql, array($email, $id));

        if(empty($result->row()))
		{
            return false;
        }
		else
		{
            return true;
		}
	}


    /**
     * 根据角色id判断是否存在属于此角色的用户
     * 
     * @param int $id  角色id
     * 
     * @return boolean true | false
     */
    public function check_exist_by_role_id($role_id)
	{
        if(empty($role_id))
		{
            return false;
        }

        $sql = "SELECT a.id FROM {$this->_table_name} AS a
					WHERE a.role_id = ? 
					LIMIT 1";

        $result = $this->db->query($sql, array($role_id));

        if(empty($result->row()))
		{
            return false;
        }
		else
		{
            return true;
		}
	}

}